package com.iakuil.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iakuil.app.common.core.util.BeanUtils;
import com.iakuil.app.domain.dto.event.OperationLogEvent;
import com.iakuil.app.domain.dto.query.OperationLogQuery;
import com.iakuil.app.domain.entity.OperationLog;
import com.iakuil.app.repository.dao.OperationLogMapper;
import com.iakuil.app.service.OperationLogService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 操作日志 服务实现类
 *
 * @author Kai
 * @since 2023-04-12
 */
@Service
public class OperationLogServiceImpl implements OperationLogService {

    private final OperationLogMapper operationLogMapper;

    public OperationLogServiceImpl(OperationLogMapper operationLogMapper) {
        this.operationLogMapper = operationLogMapper;
    }

    @Async("operateLogExecutor")
    @EventListener
    public void record(OperationLogEvent operationLogEvent) {
        OperationLog entity = BeanUtils.copy(operationLogEvent, OperationLog.class);
        entity.setOperTime(new Date());
        operationLogMapper.insert(entity);
    }

    @Override
    public List<OperationLog> listByCondition(OperationLogQuery query) {
        return operationLogMapper.selectList(new QueryWrapper<OperationLog>()
            .lambda()
            .eq(query.getTitle() != null, OperationLog::getTitle, query.getTitle())
            .eq(query.getRequestMethod() != null, OperationLog::getRequestMethod, query.getRequestMethod())
            .eq(query.getOperSource() != null, OperationLog::getOperSource, query.getOperSource())
            .likeRight(query.getOperName() != null, OperationLog::getOperName, query.getOperName())
            .eq(query.getStatus() != null, OperationLog::getStatus, query.getStatus())
            .ge(query.getSince() != null, OperationLog::getOperTime, query.getSince())
            .le(query.getUtil() != null, OperationLog::getOperTime, query.getUtil())
            .orderByDesc(OperationLog::getOperTime));
    }

    @Override
    public boolean removeById(Long id) {
        return operationLogMapper.deleteById(id) > 0;
    }
}
